<template>
<div class="goodsSKU">
  <search-block type="half">
    <template slot="button">
      <el-button type="primary" @click="createTable">生成列表</el-button>
    </template>
    <el-form :model="this" label-width="100px" inline @submit.native.prevent>
      <el-form-item
        v-for="(item, index) in selectValue"
        :key="index"
        :label="item.name + '：'">
        <el-checkbox-group v-model="item.select">
          <el-checkbox
            v-for="(itemVal, index2) in item.values"
            :key="index + '_' + index2"
            :label="JSON.stringify({value: itemVal.value, icon: itemVal.icon, id: itemVal.id})">{{itemVal.value}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
  </search-block>
  <y-table
    v-if="initColumn"
    border
    :get-data-way="{data: tableData}"
    :columns="columns">
    <el-table-column slot="skuCode" label="SKU编码" align="center" header-align="center">
      <template v-slot="{row}">
        <el-input v-if="row.edit" v-model="row.skuCode" size="mini" :maxlength="20" show-word-limit></el-input>
        <span v-else>{{row.skuCode}}</span>
      </template>
    </el-table-column>
    <el-table-column slot="price" label="价格" align="center" header-align="center" width="100">
      <template v-slot="{row}">
        <el-input-number v-if="row.edit" :controls="false" v-model="row.price" size="mini" :min="0" :step="0.01"></el-input-number>
        <span v-else>{{row.price}}</span>
      </template>
    </el-table-column>
    <el-table-column slot="stock" label="库存" align="center" header-align="center" width="100">
      <template v-slot="{row}">
        <el-input-number v-if="row.edit" step-strictly :controls="false" v-model="row.stock" size="mini" :min="0" :step="1"></el-input-number>
        <span v-else>{{row.stock}}</span>
      </template>
    </el-table-column>
    <el-table-column slot="lowStock" label="预警库存" align="center" header-align="center" width="100">
      <template v-slot="{row}">
        <el-input-number v-if="row.edit" step-strictly :controls="false" v-model="row.lowStock" size="mini" :min="0" :step="1"></el-input-number>
        <span v-else>{{row.lowStock}}</span>
      </template>
    </el-table-column>
    <el-table-column slot="y-oper" label="操作" align="center" header-align="center" width="140" v-if="!disabled">
      <template v-slot="{row}">
        <div class="table-buttons">
          <el-button v-if="!row.edit" type="primary" size="mini" @click="editSku(row)">编辑</el-button>
          <el-button v-else type="primary" size="mini" @click="saveSku(row)">保存</el-button>
          <el-popconfirm
              v-if="!row.lockStatus"
              title="是否确认删除该条数据？"
              @confirm="delSku(row)">
            <el-button slot="reference" type="danger" size="mini">删除</el-button>
          </el-popconfirm>
        </div>
      </template>
    </el-table-column>
  </y-table>
</div>
</template>

<script>
export default {
  name: "goodsSKU",
  props:{
    productId: String,
    disabled: Boolean
  },
  inject: ['refreshSku'],
  data(){
    return {
      originValue: {},
      selectValue: [],
      tableData: [],
      columns: [],
      initColumn: false,
      editing: null
    }
  },
  activated(){
    if(this.refreshSku()){
      this.$yAxios({
        url: this.$api.goods.selectSpec,
        data: {
          productId: this.productId
        },
        loading: true
      }, info => {
        this.originValue = info;
        this.$set(this, 'selectValue', this.generateSelectValue());
        //this.initTableHeader();
        this.$set(this, 'tableData', []);
        this.$emit('has-reset-sku');
      });
    }
  },
  methods:{
    generateSelectValue(){
      let ary = []
      Object.keys(this.originValue).map(key => {
        let obj = { name: key };
        obj.spCode = this.originValue[key][0].specCode;
        obj.values = this.originValue[key];
        obj.select = [];
        ary.push(obj);
      });
      return ary;
    },
    initTableHeader(spCodes){
      this.columns = [];
      this.selectValue.map(item => {
        if(spCodes.includes(item.spCode)){
          this.columns.push({
            label: item.name,
            prop: item.spCode
          });
        }
      });
      this.columns.push(...[{
        label: 'SKU编码',
        prop: 'skuCode',
        template: true
      },{
        label: '售价',
        prop: 'price',
        template: true
      },{
        label: '库存',
        prop: 'stock',
        template: true
      },{
        label: '预警库存',
        prop: 'lowStock',
        template: true
      }]);
      this.initColumn = true;
    },
    createTable(){
      let param = {};
      this.selectValue.map(({select, spCode, values}) => {
        let select2 = select.map(val => JSON.parse(val)), selectInOrder = [];
        values.map(obj => {
          let _thisSelect = select2.find(item => item.id === obj.id);
          if(!!_thisSelect){
            selectInOrder.push(_thisSelect);
          }
        })
        if(selectInOrder.length) param[spCode] = selectInOrder;
      })
      this.initTableHeader(Object.keys(param));
      this.$yAxios({
        url: this.$api.goods.skuList,
        data:{
          productId: this.productId,
          specs: param
        },
        loading: true
      }, info => {
        this.editing = null;
        this.tableData = info.record.map(item => {
          this.$set(item, 'edit', false);
          return item;
        });
      })
    },
    editSku(row){
      if(!this.editing){
        this.editing = row;
        this.$set(row, 'edit', true);
      }else{
        this.$alert('存在其他正在编辑未保存的数据，请先保存其他数据再编辑本条数据', {
          confirmButtonText: '确定'
        });
      }
    },
    saveSku(row){
      this.$yAxios({
        url: this.$api.goods.saveSku,
        data: row,
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '保存成功'
        });
        this.createTable();
      })
    },
    delSku(row){
      this.$yAxios({
        url: this.$api.goods.removeSku,
        data:{
          id: row.id
        },
        loading: true
      }, info => {
        this.$message({
          type: 'success',
          message: '删除成功'
        });
        this.createTable();
      })
    },
    save(){
      return new Promise(resolve => {
        if(this.editing){
          this.$message({
            type: 'warning',
            message: '请保存正在编辑的SKU'
          });
          resolve(false);
        }
        resolve(true);
      });
    }
  }
}
</script>

<style scoped lang="less">
.goodsSKU{
  >.SearchBlock{
    justify-content: space-between;
    align-items: flex-start;
  }
  /deep/ .el-input-number{
    width: 100%;
  }
}
</style>